import datetime

import redis
from django.conf import settings
from django_cron import CronJobBase, Schedule
from points.models import UserRanking, User
from utils.ranking_service import RankingService

class DailyRankingPersistence(CronJobBase):
    RUN_AT_TIMES = ['00:00']  # 每日0点执行

    schedule = Schedule(run_at_times=RUN_AT_TIMES)
    code = 'ranking_app.daily_ranking_persistence'  # 任务代码

    def do(self):
        service = RankingService()
        top_users = service.get_top_users()

        # 清空当日之前的排行榜数据
        UserRanking.objects.all().delete()

        # 持久化新的排行榜数据
        for rank, (user_id, score) in enumerate(top_users, start=1):
            try:
                user = User.objects.get(id=user_id)
                UserRanking.objects.create(
                    username=user,
                    points=int(score),
                    rank=rank,
                    date=settings.TIME_ZONE.localize(datetime.datetime.now()).date()
                )
            except User.DoesNotExist:
                pass